package design.chain;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yuqi<307530884@qq.com> <2017/3/22>
 * @version 1.0
 * @since 1.0
 */
public class FilterChainImpl implements FilterChain {

    private List<Filter> filterChain = new ArrayList<Filter>();

    //设置下一个过滤器的默认值为0
    private ThreadLocal<Integer> nextIndex = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    public void register(Filter filter){
        filterChain.add(filter);
    }

    public void registerAll(List<Filter> filters){
        filterChain.addAll(filters);
    }

    @Override
    public Response doFilter(Request request){
        if(nextIndex.get() >= filterChain.size()){
            System.out.println("所有过滤器都处理了一遍");
            return new Response();
        }

        int filterIndex = nextIndex.get();
        Filter next = filterChain.get(filterIndex);

        nextIndex.set(filterIndex + 1);//设置下一个过滤器的位置

        return next.doFilter(request, this);
    }

}
